package com.handpay.zztong.hp.main.widget.dialog.blur;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;

import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.main.widget.icon.IconBaseAdapter;
import com.handpay.zztong.hp.main.widget.icon.IconBaseOnItemClickListener;

import java.util.ArrayList;


/**
 * Created by chooblarin on 2014/11/19.
 */
public class BlurDialogFragment extends DialogFragment {

    private Drawable backgroundDrawable;
    private ArrayList<String> mIconData = null;
    private ZZTongActivity mActivity;

    public void setIconData(ArrayList<String> mIconData) {
        this.mIconData = mIconData;
    }

    public void fadeIn(final ZZTongActivity activity, final String tag) {
        mActivity = activity;
        final Bitmap backgroundBitmap = createBackgroundBitmap(activity);

        // create fast blur bitmap and show dialog
        new AsyncTask<Void, Void, Drawable>() {
            @Override
            protected Drawable doInBackground(Void... params) {
                Bitmap localBitmap = Blur.fastblur(activity, backgroundBitmap, 16);
                Paint paint = new Paint();
                paint.setColor(0x77000000);
                RectF rect = new RectF(0, 0, localBitmap.getWidth(), localBitmap.getHeight());
                new Canvas(localBitmap).drawRoundRect(rect, 0, 0, paint);
                return new BitmapDrawable(activity.getResources(), localBitmap);

//                return new BitmapDrawable(activity.getResources(),backgroundBitmap);
            }

            @Override
            protected void onPostExecute(Drawable drawable) {
                backgroundDrawable = drawable;
                show(activity.getSupportFragmentManager(), tag);

                if (backgroundBitmap != null) {
                    backgroundBitmap.recycle();
                }
            }
        }.execute();
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), R.style.BlurDialogStyle) {
            @Override
            public boolean onTouchEvent(@NonNull MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    boolean isOutOfBounds = isOutOfBounds(getActivity(), event);
                    if (isOutOfBounds) {
                        dismiss();
                        return true;
                    }
                }
                return super.onTouchEvent(event);
            }


            private boolean isOutOfBounds(Context context, MotionEvent event) {
                View mContentView = getWindow().getDecorView().findViewById(R.id.content_ll);
                float tLeft = mContentView.getX();
                float tTop = mContentView.getY();
                float tWidth = mContentView.getWidth();
                float tHeight = mContentView.getHeight();
                final int x = (int) event.getX();
                final int y = (int) event.getY();
                return (x < tLeft) || (y < tTop) || (x > tLeft + tWidth) || (y > tTop + tHeight);
            }
        };
        Window window = dialog.getWindow();
//        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//        );
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        dialog.setContentView(R.layout.dialog_floder_show);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // 背景透明
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        window.setBackgroundDrawable(backgroundDrawable);
        GridView icon_gw = (GridView) dialog.findViewById(R.id.icon_gridview);
        IconBaseAdapter mIconBaseAdapter = new IconBaseAdapter(getActivity());
        mIconBaseAdapter.setShowAnimator(true);
        mIconBaseAdapter.setData(mIconData);
        icon_gw.setAdapter(mIconBaseAdapter);
        dialog.setCanceledOnTouchOutside(true);
        icon_gw.setOnItemClickListener(new IconBaseOnItemClickListener(mActivity){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                super.onItemClick(adapterView, view, position, l);
                dismiss();
            }
        });
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        // no dimmed background
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams windowParams = window.getAttributes();
        windowParams.dimAmount = 0.0f;
        windowParams.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        window.setAttributes(windowParams);
    }

    private Bitmap createBackgroundBitmap(Activity activity) {
        View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
        view.setDrawingCacheEnabled(true);
        Bitmap tBitmap = view.getDrawingCache();
        // 拷贝图片，否则在setDrawingCacheEnabled(false)以后该图片会被释放掉
        tBitmap = tBitmap.createBitmap(tBitmap);
        view.setDrawingCacheEnabled(false);
        return tBitmap;
    }

    private static int getDisplayOrientation(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        switch (display.getRotation()) {
            case Surface.ROTATION_90:
            case Surface.ROTATION_270:
                return Configuration.ORIENTATION_LANDSCAPE;

            default:
                return Configuration.ORIENTATION_PORTRAIT;
        }
    }

    private static int getStatusBarHeight(Activity activity) {

        Rect rectangle = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);
        return rectangle.top;
    }

    private static int getNavigationBarHeight(Context context, int orientation) {
        Resources resources = context.getResources();

        int id = resources.getIdentifier(
                orientation == Configuration.ORIENTATION_PORTRAIT
                        ? "navigation_bar_height" : "navigation_bar_height_landscape",
                "dimen", "android");
        if (id > 0) {
            return resources.getDimensionPixelSize(id);
        }
        return 0;
    }
}
